//
//  ResultViewController.m
//  Cook
//
//  Created by 0.0 on 15-4-17.
//  Copyright (c) 2015年 dingjun. All rights reserved.
//

#import "ResultViewController.h"
#import "SecondModel.h"
#import "ResultCollectionViewCell.h"
#import "ResultModel.h"
#import "UIScrollView+PullLoad.h"
#import "DetailController.h"
#import "VegetableMenu.h"
#import "HeaderCollectionReusableView.h"
#import "MONActivityIndicatorView.h"

#define foodMenu @"http://121.41.87.4:80/HandheldKitchen/api/vegetable/tbldisease!getVegetable.do"

#define vegetableMenu @"http://121.40.54.242:80/HandheldKitchen/api/vegetable/tblvegetable!getTblVegetables.do"

@interface ResultViewController () <UICollectionViewDataSource, UICollectionViewDelegate, PullDelegate, MONActivityIndicatorViewDelegate>
{
   
    
    HeaderCollectionReusableView *_result; // 设置病症简介view
    UICollectionView *_collectionView;
    CGAdapter _myAd;
    
    NSInteger flag;
    
    UIAlertView *_fileAlertView;
    
}

@property (nonatomic, retain) NSMutableArray *foodArray;
@property (nonatomic, retain) NSString *path;

@property (nonatomic, retain) UIView *frontView;
@property (nonatomic, retain) NSTimer *netTimer;



@end

@implementation ResultViewController

- (void)dealloc
{
    [_secondModel release];
    [_foodArray release];
    [_path release];
    [_frontView release];
    [_netTimer release];
    
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        self.foodArray = [NSMutableArray array];
        self.path = [[NSBundle mainBundle] pathForResource:@"click" ofType:@"png"];
        _myAd = [AdapterModel getCGAdapter];
        flag = 0;
       
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    // 创建bar上的信息
    [self createNavigationBar];
    
    [self creatBackground];
    
    // 创建collectionView
    [self createCollectionView];
    
    [self createInvidate];

}

#pragma mark - 创建小菊花
- (void)createInvidate
{
    self.frontView = [[UIView alloc] initWithFrame:self.view.frame];
    _frontView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5f];
    [self.view addSubview:_frontView];
    [_frontView release];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification) name:@"frontView" object:nil];
    
    MONActivityIndicatorView *indicator = [[MONActivityIndicatorView alloc] init];
    indicator.delegate = self;
    indicator.numberOfCircles = 3;
    indicator.radius = 20;
    indicator.internalSpacing = 3;
    indicator.center = _frontView.center;
    
    // 隐藏顶部navigationbar
    self.navigationController.navigationBar.hidden = YES;
    
    [indicator startAnimating];
    [_frontView addSubview:indicator];
    [indicator release];
    
    self.netTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(isHaveFront) userInfo:nil repeats:NO];
}


// 加载成功
- (void)notification
{
    [_netTimer invalidate];
    self.navigationController.navigationBar.hidden = NO;
    [self.frontView removeFromSuperview];
    self.frontView = nil;
    
}

// 判断加载情况
- (void)isHaveFront
{
    if (_frontView != nil) {
        _fileAlertView = [[UIAlertView alloc] initWithTitle:@"加载失败" message:@"是否重新加载" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [_fileAlertView show];
        
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 0) {
        self.navigationController.navigationBar.hidden = NO;
        [self.navigationController popViewControllerAnimated:YES];
    }
    if (buttonIndex == 1) {
        //        [self createIndicator];
        
        //        [self.view removeFromSuperview];
        [self.frontView removeFromSuperview];
        [self viewDidLoad];
    }
    
    
    
    [_fileAlertView dismissWithClickedButtonIndex:0 animated:YES];
    [_fileAlertView release];
    
}


- (void)creatBackground
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64)];
    [imageView setImage:[UIImage imageNamed:@"secondBarBacground.jpg"]];
    [self.view addSubview:imageView];
    [imageView release];
}


- (void)createNavigationBar
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationItem.title = _secondModel.diseaseName;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"backHomePage" ofType:@"png"];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithContentsOfFile:path] style:UIBarButtonItemStylePlain target:self action:@selector(buttonClick)];
    [self.navigationItem setRightBarButtonItem:bar];
    [bar release];
    
}

- (void)buttonClick
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)createCollectionView
{
    UICollectionViewFlowLayout *myLayout = [[UICollectionViewFlowLayout alloc] init];

    myLayout.itemSize = CGSizeMake(self.view.frame.size.width *0.5 - 20, 140 * _myAd.sHeight);
    myLayout.minimumInteritemSpacing = 5.0f;
    myLayout.minimumLineSpacing = 20.0f;
    myLayout.sectionInset = UIEdgeInsetsMake(5, 0, 5, 20);
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:myLayout];
    [myLayout release];
    [_collectionView registerClass:[ResultCollectionViewCell class] forCellWithReuseIdentifier:@"resultCell"];
    [_collectionView registerClass:[HeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerCell"];
    _collectionView.backgroundColor = [UIColor clearColor];

#pragma mark - 设置有没有头view
    myLayout.headerReferenceSize = CGSizeMake(100, 100);
    
    [_collectionView setDelegate:self];
    [_collectionView setDataSource:self];
    
    [_collectionView setPullDelegate:self];
    [_collectionView setCanPullUp:YES];
    [_collectionView setCanPullDown:NO];
    
    [self.view addSubview:_collectionView];
    [_collectionView release];
    
    // 进行网络请求
    
    [self scrollView:[[[UIScrollView alloc] init] autorelease] loadWithState:PullUpLoadState];
}

- (void)startConnect:(NSDictionary *)dic
{
    __block ResultViewController *my = self;
    __block UICollectionView *myCollection = _collectionView;
    
    [MyConnection connectWithUrl:foodMenu parmaters:dic finishBlock:^(NSData *data) {
 
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = dataDic[@"data"];
        if ([array count] != 0) {
        for (NSDictionary *dDic in array) {
            ResultModel *model = [ResultModel resultModelWithVegetableId:dDic[@"vegetableId"] name:dDic[@"name"] imagePathLandscape:dDic[@"imagePathLandscape"] clickCount:dDic[@"clickCount"]];
            [my.foodArray addObject:model];

        }
            [myCollection reloadData];
            [myCollection stopLoadWithState:PullUpLoadState];
        }
        else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"没有更多的内容了" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];
            [alertView release];
            [myCollection setCanPullUp:NO];
        }
    }];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        _result = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerCell" forIndexPath:indexPath];
        
        [_result.diseaseDiscusLabel setText:self.secondModel.diseaseDescribe];
        [_result.moreButton addTarget:self action:@selector(moreButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        // 详情界面的button
        [self createBigButton];
        
        return _result;
    }

    return nil;
}

- (void)createBigButton
{
    CGRect rect = _result.frame;
    UIButton *button = [[UIButton alloc] initWithFrame:rect];
    [button addTarget:self action:@selector(moreButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    _result.userInteractionEnabled = YES;
    _result.diseaseDiscusLabel.userInteractionEnabled = YES;
    [_result.headerView addSubview:button];
    [button release];
//    [self.view addSubview:button];
    
}

- (void)moreButtonClick:(id)sender
{
    
    NSString *str = [NSString stringWithFormat:@"%@\n\t%@\n%@\n\t%@\n%@\n\t%@", @"病症简介", _secondModel.diseaseDescribe, @"饮食保健", _secondModel.fitEat, @"生活保健", _secondModel.lifeSuit];
    
    
    UIAlertView *view = [[UIAlertView alloc] initWithTitle:nil message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    
    [view show];
    [view release];
}

- (void)willPresentAlertView:(UIAlertView *)alertView
{
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.foodArray count];
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ResultCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"resultCell" forIndexPath:indexPath];
    ResultModel *model = [self.foodArray objectAtIndex:indexPath.row];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"imagePlace" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    [cell.foodImageView sd_setImageWithURL:[NSURL URLWithString:model.imagePathLandscape] placeholderImage:image];
    [cell.foodNameLabel setText:model.name];
    [cell.clickLabel setText:[NSString stringWithFormat:@"❤️ %@", model.clickCount]];
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [_collectionView deselectItemAtIndexPath:indexPath animated:YES];
    ResultModel *model = [self.foodArray objectAtIndex:indexPath.item];
    DetailController *detail = [[DetailController alloc] init];
    detail.vegetableMenuModel.vegetable_id = model.vegetableId;
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];

}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *my = [[collectionView indexPathsForVisibleItems] firstObject];
    if (indexPath.item == my.item) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"frontView" object:nil];
    }
}

//?vegetable_id=1649&phonetype=2&user_id=&is_traditional=0


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)scrollView:(UIScrollView *)scrollView loadWithState:(LoadState)state
{
    flag++;
    NSDictionary *dic = @{@"diseaseId":_secondModel.diseaseId, @"page":[NSString stringWithFormat:@"%d", flag], @"pageRecord":@"8", @"phonetype":@"0", @"is_traditional":@"0"};
    if (state == PullUpLoadState) {
        [self startConnect:dic];
    }
   
}

@end
